<?php
function array_length($arr){
    $length = 0;
    foreach($arr as $key=>$value){
        $length++;
    }
    return $length;
}

function array_implode($arr,$needle=','){
    $length = array_length($arr);
    $str = $needle;
    $i = 0;
    while($i<$length){
        $inst = $arr[$i];
        $str = $str . $inst.$needle;
        $i++;
    }
    return $str;
}
$hasError=false;

//检查用户名
//必须填写
//至少三个字符
//至多5个字符
//字母开头，字母数字，下划线
$username = trim($_POST["Username"]);
if(!$username){
    echo "用户名必须填写<br />";
    $hasError=true;
}else{
    $len = strlen($username);
    if($len<3){
        echo "用户名至少三个字符<br />";
        $hasError=true;
    }else if($len>5){
        echo "用户名最多5个字符<br />";
        $hasError=true;
    }else if(!preg_match('/^[a-zA-Z0-9_]*$/',$username)){
       echo "格式不符合要求";
       $hasError=true;
    }
}

//检查密码
//必须填写
//至少三个字符
//至多5个字符
$password = trim($_POST["Password"]);
if(!$password){
    echo "用户名必须填写<br />";
    $hasError=true;
}else{
    $len = strlen($password);
    if($len<3){
        echo "密码至少三个字符<br />";
        $hasError=true;
    }else if($len>5){
        echo "密码最多5个字符<br />";
        $hasError=true;
    }
}

$gender = $_POST["Gender"];
if($gender=='male') $gender = 1;
else if($gender=='female') $gender = 0;
else $gender = -1;

//岁数
//可以不填写
//如果填写必须是数字
$age = trim($_POST["Age"]);
if($age){
    $ageNum = intval($age);
    if(!$ageNum||$ageNum<=0||$ageNum>200){
        echo "请填写正确的岁数<br />";
        $hasError=true;
    }
}

$interests = $_POST["Interests"];

$length = array_length($interests);

if($length<2){
    echo "兴趣必须填写2个<br />";
    $hasError=true;
}else if($length>3){
    echo "兴趣最多填写3个<br />";
    $hasError=true;
}
$interestStr = array_implode($interests,"|");

$province = $_POST["Province"];
$intro = $_POST["Intro"];

if(!$hasError){
    $intro = str_replace("'","''",$intro);
    $sql = "INSERT INTO `Account` (`Username`,`Password`,`Gender`,`Interest`,`Intro`)
    VALUES ('$username','$password','$gender','$insterestStr','$intro')";
    echo $sql;
    $sqli = new mysqli("localhost","root","","myblog");
    $sqli->query($sql);
    if($sqli->error) echo $sqli->error;
    echo "注册成功<br />";
}

//if(!$hasError) echo "检查成功";

echo "<a href='form.html'>返回</a>";